import { UserConfig, ConfigEnv } from 'vite'
import { createVitePlugins } from './config/vite/plugins'
import { VITE_DROP_CONSOLE, VITE_PORT } from './config/constant'
import path from 'path'
import proxy from './config/vite/proxy'
import { generateModifyVars } from './config/themeConfig'

function resovePath(paths: string) {
  return path.resolve(__dirname, paths)
}

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const isBuild = command === 'build'
  return {
    base: '/',
    plugins: createVitePlugins(isBuild),
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '@config': resovePath('./config'),
        '@components': resovePath('./src/components'),
        '@utils': resovePath('./src/utils'),
        '@api': resovePath('./src/api'),
        '@assets': resovePath('./src/assets'),
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: generateModifyVars(),
          javascriptEnabled: true,
        },
      },
    },
    // local proxy
    server: {
      // Disable or configure the HMR connection Set server.hmr.overlay to false to disable the server error overlay
      hmr: { overlay: false },
      // service configuration
      port: VITE_PORT,
      // Type: boolean | string Automatically at server startup
      open: false,
      // Type: boolean | CorsOptions Configures CORS for the development server. Enabled by default and allows any origin
      cors: true,
      // IP configuration, support booting from IP
      host: '127.0.0.1',
      proxy,
      // https: true,
      headers: {
        'Cross-Origin-Embedder-Policy': 'credentialless',
        'Cross-Origin-Opener-Policy': 'same-origin',
      },
    },
    build: {
      target: 'es2015',
      terserOptions: {
        compress: {
          keep_infinity: true,
          // Delete the console of the production environment
          drop_console: VITE_DROP_CONSOLE,
        },
      },
      // Turning off brotliSize display can slightly reduce packaging time
      brotliSize: false,
      chunkSizeWarningLimit: 2000,
      sourcemap: false,
    },
  }
}
